package util.src.com;

/**
 * @Author: Gosin
 * @Date: 2020/10/30 9:59
 */

public class DownloadScheduleThread extends Thread {
    static int maxIndex = 100;    //控制输出的进度条宽度
    public final int allTsNum;
    public int doneNum;
    public ReturnDoneNum obj;

    public DownloadScheduleThread(int allTsNum, ReturnDoneNum obj) {
        this.allTsNum = allTsNum;
        this.obj = obj;
    }

    @Override
    public void run() {

        int c = 0;
        String d;
        StringBuffer kg = new StringBuffer();
        for (int i = 0; i < maxIndex; i++) {
            kg.append(" ");
        }
        System.out.print("00%[>" + kg.toString() + "]");
        while (c < 101) {
            doneNum = obj.returnDoneNum();
            c = (int) (100 * (doneNum) / (float) allTsNum);
            d = (doneNum) + "/" + allTsNum;
            printCurrentNum(c, d);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
            }
            if (c == 100) {//当下载进度是100时，所以程序退出
                System.exit(1);
            }
        }
    }

    private void focusGoto() {
        for (int i = maxIndex + 6 + 9; i > 0; i--) {
            System.out.print('\b');
        }
    }

    private void printCurrentNum(int i, String d) {
        String num = "000" + i;
        num = num.substring(num.length() - 3);
        StringBuffer s = new StringBuffer(num + "%[");
        focusGoto();
        int prec = (i * 100) / 100;
        for (int index = 0; index < maxIndex; index++) {
            int c = (index * 100) / maxIndex;
            if (c < prec) {
                s.append("■");
            } else {
                s.append(" ");
            }
        }
        s.append("]");
        s.append(d);
        System.out.print(s.toString());
    }

}